package com.atguigu.Base;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class SyncVSLockDemo {

    //==========================================================================================
    public synchronized void method1() {
        System.out.println(Thread.currentThread().getName() + "老子进来了");
        //让线程休息一下
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //==========================================================================================
    private final Lock lock = new ReentrantLock();

    //ctrl+F12查找方法

    public void method2()  {
        if (lock.tryLock()) {
            try {
                System.out.println(Thread.currentThread().getName() + "老子进来了");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "等待锁");
        }

    }
    //==========================================================================================

    public void method3() {
        try {
            if (lock.tryLock(4,TimeUnit.SECONDS)) {
                try {
                    System.out.println(Thread.currentThread().getName() + "老子进来了");
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } finally {
                    lock.unlock();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "等待锁");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        SyncVSLockDemo demo = new SyncVSLockDemo();
        new Thread(demo::method3,"A").start();
        new Thread(demo::method3,"B").start();
    }
}